clc;
close all;
clear all;

N = 4;
k = 1;
lower = 0.0;
upper = 0.9999999999;
step = 2^(-N);
qtl = 2^(-N-k);
C = 4 * qtl;
ulp = 2^(-N);
num = (floor((upper-lower)/step) + 1);


P = 0:.01:1;
num_exp = length(P);
err_rnd = zeros(num_exp);
err_red = zeros(num_exp);
ulp_line = ones(num_exp) * ulp;

for i = 1:num_exp
	[err_rnd(i),err_red(i)] = ccm_const_prob(N,N,N,k,P(i));
end

%% Plot 
h1 = figure(1);
plot(err_rnd, 'k');hold on;
plot(err_red, 'g');hold on;
plot(err_rnd + err_red, 'b');hold on;
plot(ulp_line, 'r');
legend('err_rnd', 'err_red', 'err_total', 'ulp');
title(strcat('CCT constant vs. Probability p <N=' , num2str(N) , ',k=' , num2str(k) , '>'));
savefig(h1, 'fig1.cct_constant.fig');

diff = zeros(num,num);
index = 0;
[cct_rnd, cct_red] = ccm_const_prob(N, N, N, k, 0.7);
cct = cct_rnd + cct_red;
for a = lower:step:upper
    for b = lower:step:upper
        index = index + 1;
        ans_true = a * b;
        ans_trunc = trunc_mult(a, b, 0.0, N, N, N, k);
        diff(index) = abs(ans_true - ans_trunc);                
    end
end

err = diff - ones(num,num) * cct;

h2 = figure(2);
plot(diff(:), 'r-o'); 
legend('diff = |true - trunc|');
title(strcat('diff = |true - trunc| <N=' , num2str(N) , ',k=' , num2str(k) , '>'));
savefig(h2,'fig2.diff.fig');

h3 = figure(3);
plot(err(:), 'b-+');hold on;
ulp_mt = ulp * ones(num^2, 1);
plot(ulp_mt(:), 'r-+');hold on;
plot(-1 * ulp_mt(:), 'r-');
legend('err', '+1ulp', '-1ulp');
title(strcat('diff - const <N=' , num2str(N) , ',k=' , num2str(k) , '>'));
savefig(h3,'fig3.diff_const.fig');